from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from sqlalchemy import desc
from app.models import Banner, AdminLog
from app.core.extensions import db
from . import admin_blueprint
from app.services.decorators import admin_required


@admin_blueprint.route('/banners', methods=['GET', 'OPTIONS', 'POST'])
@jwt_required(optional=True)
def banners_endpoint():
    """轮播图接口
    
    GET: 获取轮播图列表
    POST: 添加新轮播图
    """
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})

    # GET请求：获取列表
    if request.method == 'GET':
        # 获取分页参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        status = request.args.get('status', None, type=int)

        # 构建查询
        query = Banner.query

        # 根据状态筛选
        if status is not None:
            query = query.filter(Banner.status == status)

        # 执行分页查询
        pagination = query.order_by(Banner.sort.desc(), desc(Banner.id)).paginate(
            page=page, per_page=per_page, error_out=False
        )

        banners = pagination.items

        # 构建响应数据
        result = {
            'code': 0,
            'message': '获取成功',
            'data': {
                'total': pagination.total,
                'pages': pagination.pages,
                'page': page,
                'per_page': per_page,
                'items': [banner_to_dict(banner) for banner in banners]
            }
        }

        return jsonify(result)

    # POST请求：添加新轮播图
    elif request.method == 'POST':
        # 检查管理员权限
        jwt_data = get_jwt()
        if jwt_data.get('is_test', False):
            return jsonify({'code': 1, 'message': '测试账号无权限添加轮播图'}), 403

        data = request.json

        # 提取表单数据
        title = data.get('title', '')
        image_url = data.get('image_url')
        link_url = data.get('link_url', '')
        sort = data.get('sort', 0)
        status = data.get('status', 1)

        # 验证必要参数
        if not image_url:
            return jsonify({'code': 1, 'message': '图片URL不能为空'}), 400

        # 创建新轮播图
        banner = Banner(
            title=title,
            image_url=image_url,
            link_url=link_url,
            sort=sort,
            status=status
        )

        db.session.add(banner)

        # 添加操作日志
        log = AdminLog(
            admin_id=get_jwt_identity(),
            action='添加轮播图',
            ip=request.remote_addr,
            details=f'添加轮播图 {title}'
        )
        db.session.add(log)

        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '添加成功',
            'data': banner_to_dict(banner)
        })


@admin_blueprint.route('/banners/<int:banner_id>', methods=['GET', 'OPTIONS', 'PUT'])
@jwt_required(optional=True)
@admin_required
def get_banner(banner_id):
    """轮播图详情操作
    
    GET: 获取轮播图详情
    PUT: 更新轮播图信息
    """
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})

    banner = Banner.query.get(banner_id)

    # GET请求：获取详情
    if request.method == 'GET':
        return jsonify({
            'code': 0,
            'message': '获取成功',
            'data': banner_to_dict(banner)
        })

    # PUT请求：更新轮播图
    elif request.method == 'PUT':
        # 检查管理员权限
        jwt_data = get_jwt()
        if jwt_data.get('is_test', False):
            return jsonify({'code': 1, 'message': '测试账号无权限修改轮播图'}), 403

        data = request.json

        # 更新轮播图信息
        if 'title' in data:
            banner.title = data['title']
        if 'image_url' in data:
            banner.image_url = data['image_url']
        if 'link_url' in data:
            banner.link_url = data['link_url']
        if 'sort' in data:
            banner.sort = data['sort']
        if 'status' in data:
            banner.status = data['status']
        if 'hex' in data:
            banner.hex = data['hex']
        # 添加操作日志
        log = AdminLog(
            admin_id=get_jwt_identity(),
            action='编辑轮播图',
            ip=request.remote_addr,
            details=f'编辑轮播图 (ID: {banner.id})'
        )
        db.session.add(log)

        db.session.commit()

        return jsonify({
            'code': 0,
            'message': '更新成功',
            'data': banner_to_dict(banner)
        })


@admin_blueprint.route('/banners/delete/<int:banner_id>', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def delete_banner(banner_id):
    """删除轮播图"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})

    # 先获取轮播图对象
    banner = Banner.query.get(banner_id)
    if not banner:
        return jsonify({'code': 1, 'message': '轮播图不存在'}), 404

    # 添加操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='删除轮播图',
        ip=request.remote_addr,
        details=f'删除轮播图 {banner.title} (ID: {banner.id})'
    )
    db.session.add(log)

    # 删除轮播图
    db.session.delete(banner)
    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '删除成功'
    })


@admin_blueprint.route('/banners/status/<int:banner_id>', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def update_banner_status(banner_id):
    """更新轮播图状态"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})

    # 先获取轮播图对象
    banner = Banner.query.get(banner_id)
    if not banner:
        return jsonify({'code': 1, 'message': '轮播图不存在'}), 404
    data = request.json

    if 'status' not in data:
        return jsonify({'code': 1, 'message': '状态参数不能为空'}), 400

    status = data['status']
    banner.status = status

    # 添加操作日志
    status_text = '启用' if status == 1 else '禁用'
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action=f'{status_text}轮播图',
        ip=request.remote_addr,
        details=f'{status_text}轮播图 {banner.title} (ID: {banner.id})'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功',
        'data': banner_to_dict(banner)
    })


@admin_blueprint.route('/banners/sort', methods=['POST', 'OPTIONS'])
@jwt_required(optional=True)
@admin_required
def sort_banners():
    """批量更新轮播图排序"""
    # 处理OPTIONS请求
    if request.method == 'OPTIONS':
        return jsonify({'code': 0, 'message': 'OK'})

    data = request.json

    if not isinstance(data, list):
        return jsonify({'code': 1, 'message': '参数格式错误'}), 400

    for item in data:
        banner_id = item.get('id')
        sort = item.get('sort')

        if banner_id and sort is not None:
            banner = Banner.query.get(banner_id)
            if banner:
                banner.sort = sort

    # 添加操作日志
    log = AdminLog(
        admin_id=get_jwt_identity(),
        action='更新轮播图排序',
        ip=request.remote_addr,
        details='批量更新轮播图排序'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功'
    })


def banner_to_dict(banner):
    """将轮播图对象转换为字典"""
    return {
        'id': banner.id,
        'title': banner.title,
        'image_url': banner.image_url,
        'link_url': banner.link_url,
        'sort': banner.sort,
        'status': banner.status,
        'hex': banner.hex
    }
